import type { Middleware } from "@koa/router";
import AppError from "@/common/error";
import type { AppContext, AppState } from "@/common/routes";

type Options = {
  required: boolean;
};

const makeAuthMW: (o: Options) => Middleware<AppState, AppContext> = ({ required }) => {
  return async (ctx, next) => {
    const token = ctx.cookies.get("token");
    ctx.token = token;

    if (required) {
      if (token !== "admin") {
        throw AppError.unauthenticated401();
      }
    }

    await next();
  };
};

export const auth = makeAuthMW({ required: true });

export const authOptional = makeAuthMW({ required: false });

export const getToken = (ctx: AppContext): string => {
  const token = ctx.token;
  if (!token) {
    throw AppError.unauthenticated401();
  }
  return token;
};

export const tryGetToken = (ctx: AppContext): string | undefined => {
  return ctx.token;
};
